package com.justerdu.mvpclient.login.model;

import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

/**
 * @Author JusterDu 2016/11/19.
 * @Func User Model层接口实现
 */
public class UserModel implements IUserModel {

	private String username;
	private String password;
	public static String loginStatus = null;
	public static String urlPath;
	private static final String TAG = "UserModel";

	@Override
	public String login(String username, String password){
		urlPath = "http://10.141.54.55:8081/AndroidBackStage/login?username="+ username +"&password=" + password;
		Log.d(TAG, "login: urlPath: " + urlPath);
		sendRequestWithHttpClient();
		try {
			// 等待全部子线程执行完毕
			TimeUnit.MILLISECONDS.sleep(800);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return loginStatus;
	}

	private void sendRequestWithHttpClient() {
		// 开启线程来发起网络请求
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					HttpClient httpClient = new DefaultHttpClient();
					// 指定访问的服务器地址
					HttpGet httpGet = new HttpGet(urlPath);
					HttpResponse httpResponse = httpClient.execute(httpGet);
					if (httpResponse.getStatusLine().getStatusCode() == 200) {
						HttpEntity entity = httpResponse.getEntity();
						String response = EntityUtils.toString(entity, "utf-8");
						parseJSONWithJSONObject(response);
					}else{
						loginStatus = "NETWORK_ERROR";
					}
				} catch (Exception e) {
					loginStatus = "NETWORK_ERROR";
					e.printStackTrace();
				}
			}
		}).start();

	}

	private Boolean parseJSONWithJSONObject(String jsonData) {
		try {
			JSONObject jsonObject = new JSONObject(jsonData);
			String rLoginStatus = jsonObject.getString("loginStatus");
			loginStatus = rLoginStatus;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
